package com.example.demo.repository;

/**
 * @author Merlin
 * @Title: UserRepository
 * @ProjectName 001spring-boot2-demo
 * @Description: TODO
 * @date 2018/6/2514:30
 */

import com.example.demo.domain.User;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * {@link User} {@link Repository}
 */
@Repository
public class UserRepository {


    /**
     * 采用内存型的存储方法 ——> Map
     */
    private  final ConcurrentMap<Integer,User> repository = new ConcurrentHashMap<>();


    /**
     * id生成器
     */
    public static final AtomicInteger idGenerator = new AtomicInteger();

    /**
     * 保存用户对象
     * @param user {@link User}对象
     * @return 如果保存成功，返回<code>true</code>
     *          否则，返回<code>false</code>
     */
    public boolean save(User user){
        //id 从1开始
        Integer id = idGenerator.incrementAndGet();
        //设置用户ID
        user.setId(id);
        return repository.put(id,user) == null;
    }

    /**
     * 返回所有用户列表
     * @return
     */
    public Collection<User> findAll(){
        return repository.values();
    }
}
